import os
import sys



class GetInput(object):
    def __init__(self):
        self.qdict = {}
        self.type_dict = {'binary': self._binary,
                          'file': self._fname,
                          'multi': self._multi,
                          'text': self._text
                          }

    def add(self, question, answer):
        self.qdict[question] = answer

    def ask(self, question, atype, akey=None):
        """ Takes a question to ask and response type.  Returns an answer. """
        self.question = question
        self.atype = atype
        self.akey = akey
        try:
            print ''
            print question
            answer = raw_input('>')
        except KeyboardInterrupt:
            print 'Input not recognized. Input valid response or type \'q\' to quit.'
            self.ask(self.question, self.atype, self.akey)
        else:
            if answer == 'q': sys.exit()
            if self.akey and answer not in self.akey:
                print 'Response not in accepted answer list.'
                self.ask(self.question, self.type, self.akey)
            self.qdict[question] = answer
            return (self.type_dict[atype](answer, akey))

    def _multi(self, answer, akey):
        """ Ask the user a multiple choice question. """
        if answer not in akey:
            print 'Response is not acceptable.'
            print ''
            return self.ask(self.question, 'multi', akey)
        return answer


    def _binary(self, answer, akey=None):
        """ Ask the user a question with a yes or no response.
            Store the question and answer in self.qdict. """
        pos = ['Y', 'y', 'YES', 'yes', 'Yes']
        neg = ['N', 'n', 'NO', 'No', 'no']
        if answer in pos: return True
        elif answer in neg: return False
        else:
            print 'Response not in accepted answer list.'
            print ''
            return self.ask(self.question, 'binary')

    def _fname(self, answer, akey=None):
        """ Ask the user a question where the answer is a filename.
            Verify the filename exists.
            Store the question and answer in self.qdict. """
        if '.csv' not in answer:
            print 'Only CSV files are accepted.'
            print ''
            return self.ask(self.question, 'file')
        elif not os.path.exists(answer):
            print 'File not found.'
            print ''
            return self.ask(self.question, 'file')
        else: return answer

    def _text(self, answer, akey=None):
        """ Return raw text. """
        return answer   